package cn.wolfcode.shop.cloud.service.impl;

import cn.wolfcode.shop.cloud.BusinessException;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.mapper.OrderInfoMapper;
import cn.wolfcode.shop.cloud.msg.SecKillCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISecKillGoodsService;
import cn.wolfcode.shop.cloud.service.ISecKillOrderService;
import cn.wolfcode.shop.cloud.util.IdGenerateUtil;
import cn.wolfcode.shop.cloud.vo.SecKillGoodVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class  OrderInfoServiceImpl implements IOrderInfoService {


    @Autowired
    private ISecKillGoodsService secKillGoodsService;

    @Autowired
    private ISecKillOrderService secKillOrderService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;


    @Override
    @Transactional
    public String seckill(Long userId, Long seckillId) {

        //减少库存-1
        int count = secKillGoodsService.decrCount(seckillId);
        if (count == 0) {
            throw new BusinessException(SecKillCodeMsg.KILL_STOCK_OVER);
        }
        //创建订单信息
        String orderNo = createOrderInfo(userId, seckillId);

        //创建秒杀订单信息
        secKillOrderService.createSeckillOrder(userId, seckillId, orderNo);
        return orderNo;
    }

    @Override
    public OrderInfo find(String orderNo) {
        return orderInfoMapper.find(orderNo);
    }


    @Override
    public int changeOrderInfoStatus(String orderNo, Integer status) {
        return orderInfoMapper.changeOrderInfoStatus(orderNo,status);
    }


    private String createOrderInfo(Long userId, Long seckillId) {
        SecKillGoodVO seckillGoodVO = secKillGoodsService.find(seckillId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setGoodCount(seckillGoodVO.getStockCount());
        orderInfo.setGoodId(seckillGoodVO.getGoodId());
        orderInfo.setGoodImg(seckillGoodVO.getGoodImg());
        orderInfo.setGoodName(seckillGoodVO.getGoodName());
        orderInfo.setGoodPrice(seckillGoodVO.getGoodPrice());
        orderInfo.setOrderNo(new IdGenerateUtil().nextId() + "");
        orderInfo.setSeckillPrice(seckillGoodVO.getSeckillPrice());
        orderInfo.setUserId(userId);
        orderInfoMapper.save(orderInfo);
        return orderInfo.getOrderNo();
    }

}
